<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="520"
    :close-on-click-modal="false"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div>
      <el-form
        ref="formRef"
        :model="formValues"
        :rules="rules"
        label-position="top"
        label-width="120px"
      >
        <el-form-item label="运输方式" prop="transport_type">
          <el-select
            v-model="formValues.transport_type"
            placeholder="请选择"
            clearable
            filterable
            style="width: 100%"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in option['transport_type']"
              :key="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="国家" prop="country_code">
          <!-- <el-select
            v-model="formValues.country_code"
            placeholder="请选择"
            @change="handleFeeType"
            clearable
            multiple
            collapse-tags
            collapse-tags-tooltip
            filterable
            style="width: 100%"
          >
            <el-option
              :label="item.label"
              :value="item.value"
              v-for="item in option['country']"
              :key="item"
            />
          </el-select> -->
          <el-cascader
            :options="countryData"
            v-model="formValues.country_code"
            :props="countryProps"
            collapse-tags
            collapse-tags-tooltip
            clearable
            filterable
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="最小发货量">
          <VGroup style="width: 100%">
            <el-select
              v-model="formValues.shipping_unit"
              placeholder="请选择"
              clearable
              filterable
            >
              <el-option
                :label="item.label"
                :value="item.value"
                v-for="item in option['country_shipping_unit']"
                :key="item"
              />
            </el-select>
            <el-input-number
              v-model="formValues.min_shipping_value"
              :controls="false"
              :min="0"
              style="width: 100%"
            />
          </VGroup>
        </el-form-item>
        <el-form-item label="海外仓目标时效">
          <el-input-number
            v-model="formValues.ow_target_time_limit"
            :controls="false"
            placeholder="请输入"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="亚马逊目标时效">
          <el-input-number
            v-model="formValues.amazon_target_time_limit"
            :controls="false"
            placeholder="请输入"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formValues.remark"
            :rows="2"
            type="textarea"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from "element-plus";
const props = defineProps({
  id: { type: [String, Number], default: "" },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  option: { type: Object, default: () => ({}) },
});
import {
  countryMinimumAdd,
  countryMinimumEdit,
  countryMinimumDetail,
} from "../api.js";
import { isMap } from "@/data/index.js";
const { option } = toRefs(props);
const isEdit = computed(() => {
  return !!props.id;
});
const countryProps = {
  multiple: true,
  value: "value",
  label: "label",
  children: "children",
};
const formRef = ref();
const formValues = ref({});
const loading = ref();
const emit = defineEmits(["update:modelValue", "refresh", "close"]);
const rules = reactive({
  transport_type: [
    { required: true, message: "请选择运输方式", trigger: "change" },
  ],
  country_code: [{ required: true, message: "请选择国家", trigger: "change" }],
  min_shipping_value: [
    { required: true, message: "请输入最小发货量", trigger: "change" },
  ],
});
watch(
  () => props.id,
  (val) => {
    if (val) {
      getDetail(val);
    }
  }
);
const countryData = computed(() => {
  const countries = option.value.country;
  const usRegions = option.value.conf_country_region;
  const usItem = countries.find((item) => item.value === "US");
  if (usItem) {
    usItem.children = usRegions;
  }
  return countries;
});
const getDetail = async (id) => {
  const { data } = await countryMinimumDetail({ id });
  const {
    country_code,
    country_region,
    ow_target_time_limit,
    amazon_target_time_limit,
    min_shipping_value,
  } = data;
  let country_code_list = country_code;
  let country_region_list = country_region;
  let ow_target_time_limit_num = Number(ow_target_time_limit || 0);
  let amazon_target_time_limit_num = Number(amazon_target_time_limit || 0);
  let min_shipping_value_num = Number(min_shipping_value || 0);
  let country_code_data = [];
  country_code_list?.forEach((item) => {
    if (item == "US") {
      if (country_region_list?.length) {
        let arr = [];
        country_region_list?.forEach((it) => {
          arr.push([item, it]);
        });
        country_code_data.push(...arr);
      } else {
        country_code_data.push([item]);
      }
    } else {
      country_code_data.push([item]);
    }
  });
  formValues.value = {
    ...data,
    country_code: country_code_data,
    ow_target_time_limit: ow_target_time_limit_num,
    amazon_target_time_limit: amazon_target_time_limit_num,
    min_shipping_value: min_shipping_value_num,
  };
};
const handleSave = async () => {
  try {
    formRef.value?.validate(async (valid) => {
      if (valid) {
        if (
          formValues.value?.min_shipping_value &&
          !formValues.value?.shipping_unit
        ) {
          return ElMessage.warning("请选择单位");
        }
        const { country_code } = formValues.value;
        let arr = country_code;
        const uniqueCountryCodes = new Set();
        let country_region_data = [];
        arr?.forEach(([code, region]) => {
          if (code) {
            uniqueCountryCodes.add(code);
          }
          if (region) {
            country_region_data.push(region);
          }
        });
        const country_code_data = Array.from(uniqueCountryCodes);
        let from = {
          ...formValues.value,
          country_code: country_code_data,
          country_region: country_region_data,
        };
        const { code, message } = await (isEdit.value
          ? countryMinimumEdit
          : countryMinimumAdd)(from);
        if (code !== 200) {
          ElMessage.error(message);
          return;
        }
        ElMessage.success(isEdit.value ? "修改成功" : "保存成功");
        handleClose(true);
      } else {
        return false;
      }
    });
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formValues.value = { country_code: [] };
  await nextTick();
  formRef.value?.resetFields();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>
<style lang="scss" scoped>
.space {
  margin-right: 8px;
}
.space-width {
  width: 150px;
}
</style>
